package com.wnxy.admin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnxy.admin.common.handler.Asserts;
import com.wnxy.admin.common.handler.BusinessEnum;
import com.wnxy.admin.common.util.AliOssUtil;
import com.wnxy.admin.dto.MaintenancePersonDto;
import com.wnxy.admin.dto.PageResult;
import com.wnxy.admin.entity.MaintenancePersonnel;
import com.wnxy.admin.entity.MaintenanceTasks;
import com.wnxy.admin.mapper.MaintenancePersonnelMapper;
import com.wnxy.admin.mapper.MaintenanceTasksMapper;
import com.wnxy.admin.service.IMaintenancePersonnelService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author All
 * @since 2023-11-29
 */
@Service
@RequiredArgsConstructor
public class MaintenancePersonnelServiceImpl extends ServiceImpl<MaintenancePersonnelMapper, MaintenancePersonnel> implements IMaintenancePersonnelService {

    private final MaintenancePersonnelMapper maintenancePersonnelMapper;
    private final MaintenanceTasksMapper maintenanceTasksMapper;
    private final RedisTemplate<String, String> redisTemplate;
    private final AliOssUtil aliOssUtil;

    /*
     *  获取所有状态为空闲的运维人员
     * */
    @Override
    public List<MaintenancePersonnel> getAllIdleStaff() {
        return maintenancePersonnelMapper.selectList(Wrappers.lambdaQuery(MaintenancePersonnel.class)
                .eq(MaintenancePersonnel::getStatus, 2)
                .eq(MaintenancePersonnel::getFlag, 0));
    }

    @Override
    public List<MaintenancePersonnel> getIdlePeople(Long operatorId) {
        List<MaintenancePersonnel> maintenancePersonnelList = maintenancePersonnelMapper.selectList(Wrappers.lambdaQuery(MaintenancePersonnel.class)
                .eq(MaintenancePersonnel::getStatus, 2)
                .ne(MaintenancePersonnel::getOperatorId, operatorId)
                .eq(MaintenancePersonnel::getFlag, 0));

        MaintenancePersonnel personnel = maintenancePersonnelMapper.selectById(operatorId);
        maintenancePersonnelList.add(personnel);

        return maintenancePersonnelList;
    }

    @Override
    @Transactional
    public void addPerson(MaintenancePersonnel maintenancePersonnel) {
        //查询所有运维人员
        List<MaintenancePersonnel> maintenancePersonnelList = maintenancePersonnelMapper.selectList(Wrappers.lambdaQuery(MaintenancePersonnel.class)
                .eq(MaintenancePersonnel::getFlag, 0));

        String email = maintenancePersonnel.getContactEmail();

        //遍历集合,判断传入对象的邮箱是否重复
        maintenancePersonnelList.forEach(e -> {
            Asserts.fail(e.getContactEmail().equals(email), BusinessEnum.MAILBOX_ALREADY_EXISTS);
        });

        //无法添加状态为维修中的运维人员
        Asserts.fail(maintenancePersonnel.getStatus() == -1, BusinessEnum.UNABLE_TO_ADD_THIS_STATUS);

        //生成雪花id(员工编号)
        Snowflake snowflake = IdUtil.getSnowflake(6, 6);
        long userNumber = snowflake.nextId();

        if(!StringUtils.isEmpty(maintenancePersonnel.getImage())) {
            //将图片路径存入redis
            redisTemplate.opsForSet().add("save-person-file-db", maintenancePersonnel.getImage());
        }
        maintenancePersonnel.setUserNumber("CDZWW" +String.valueOf(userNumber));
        maintenancePersonnelMapper.insert(maintenancePersonnel);
    }

    @Override
    @Transactional
    public void removeBatchPerson(List<Long> maintenancePersonnelIds) {
        //遍历集合,根据id查询运维人员
        maintenancePersonnelIds.forEach(e -> {
            MaintenancePersonnel personnel = maintenancePersonnelMapper.selectById(e);

            //判断运维人员状态,只能删除禁用状态的运维人员(逻辑删除)
            Asserts.fail(personnel.getStatus() != 0, BusinessEnum.UNABLE_TO_DELETE_NON_DISABLED_PEOPLE);

            //删除图片信息
            aliOssUtil.deleteImg(personnel.getImage());
            personnel.setFlag(personnel.getOperatorId().intValue());
            maintenancePersonnelMapper.updateById(personnel);
        });
    }

    @Override
    @Transactional
    public void editPerson(MaintenancePersonnel maintenancePersonnel) {
        //根据id查询运维人员
        MaintenancePersonnel dbPersonnel = maintenancePersonnelMapper.selectById(maintenancePersonnel.getOperatorId());

        MaintenanceTasks maintenanceTasks = maintenanceTasksMapper.selectOne(Wrappers.lambdaQuery(MaintenanceTasks.class)
                .eq(MaintenanceTasks::getTaskOperatorId, maintenancePersonnel.getOperatorId())
                .eq(MaintenanceTasks::getStatus, -1)
                .eq(MaintenanceTasks::getFlag, 0));

        //无法修改处于维修中且有处理中任务的运维人员的状态
        Asserts.fail(dbPersonnel.getStatus() == -1 && !maintenancePersonnel.getStatus().equals(dbPersonnel.getStatus())
                        && !ObjectUtils.isEmpty(maintenanceTasks),
                BusinessEnum.PERSONNEL_IN_MAINTENANCE_MODE);

        //查询所有运维人员
        List<MaintenancePersonnel> maintenancePersonnelList = maintenancePersonnelMapper.selectList(Wrappers.lambdaQuery(MaintenancePersonnel.class)
                .eq(MaintenancePersonnel::getFlag, 0));

        //遍历集合,判断修改对象的邮箱是否已重复 且重复数据的id与修改对象的id不等
        maintenancePersonnelList.forEach(e -> {
            Asserts.fail(e.getContactEmail().equals(maintenancePersonnel.getContactEmail()) && e.getOperatorId() != maintenancePersonnel.getOperatorId(),
                    BusinessEnum.MAILBOX_ALREADY_EXISTS);
        });

        //修改人员对象
        maintenancePersonnelMapper.updateById(maintenancePersonnel);
    }

    @Override
    public PageResult queryPerson(MaintenancePersonDto maintenancePersonDto) {
        Page page = Page.of(maintenancePersonDto.getPageNum(), maintenancePersonDto.getPageSize());

        //根据运维人员 编号/姓名/邮箱/证书信息/人员类别 模糊匹配
        Page result = maintenancePersonnelMapper.selectPage(page, Wrappers.lambdaQuery(MaintenancePersonnel.class)
                .like(!StringUtils.isEmpty(maintenancePersonDto.getUserNumber()), MaintenancePersonnel::getUserNumber, maintenancePersonDto.getUserNumber())
                .like(!StringUtils.isEmpty(maintenancePersonDto.getUserName()), MaintenancePersonnel::getUserName, maintenancePersonDto.getUserName())
                .like(!StringUtils.isEmpty(maintenancePersonDto.getCertificate()), MaintenancePersonnel::getCertificate, maintenancePersonDto.getCertificate())
                .like(!StringUtils.isEmpty(maintenancePersonDto.getContactEmail()), MaintenancePersonnel::getContactEmail, maintenancePersonDto.getContactEmail())
                .like(!StringUtils.isEmpty(maintenancePersonDto.getPersonnelCategory()), MaintenancePersonnel::getPersonnelCategory, maintenancePersonDto.getPersonnelCategory())
                .eq(MaintenancePersonnel::getFlag, 0));

        return new PageResult<>(result.getTotal(), result.getRecords());
    }
}
